package com.jhy.guavacase.io;


import com.google.common.base.Charsets;
import com.google.common.io.CharSink;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author jhy
 * @ClassName CharSinkCase.java
 * @Description CharSink的相关示例
 * @createTime 2022年03月14日 17:01:00
 */
public class CharSinkCase {


    //1.测试CharSink中的writer功能
    @Test
    public void testCharSinkWriter() throws IOException {

        File file = new File("E:\\java项目\\Guava学习\\guava-case\\guava-case\\src\\main\\resources\\io\\charSink.txt");
        //为了保证单元测试前后环境一致，方法退出删除该文件
        file.deleteOnExit();

        //使用Files来创建一个CharSink
        CharSink charSink = Files.asCharSink(file,Charsets.UTF_8);

        String content = "CharSink-->Writer   CharSource-->Reader";
        charSink.write(content);
        Assertions.assertTrue(file.exists());

        CharSource charSource = Files.asCharSource(file,Charsets.UTF_8);
        String read = charSource.read();
        Assertions.assertEquals(read,content);
    }

    //2.测试CharSink中的writeLines功能
    @Test
    public void testCharSinkWriteLines() throws IOException {

        File file = new File("E:\\java项目\\Guava学习\\guava-case\\guava-case\\src\\main\\resources\\io\\charSink.txt");
        file.deleteOnExit();

        //使用Files来创建一个CharSink
        CharSink charSink = Files.asCharSink(file,Charsets.UTF_8);
        List<String> list = Arrays.asList("java", "c++", "python");
        charSink.writeLines(list,",");
        Assertions.assertTrue(file.exists());

    }
}
